import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon

# 设置中文字体支持
plt.rcParams['font.sans-serif'] = ['SimHei']  # 使用黑体
plt.rcParams['axes.unicode_minus'] = False    # 正确显示负号

# 定义原始基向量和变换后的基向量
original_basis = np.array([[1, 0], [0, 1]])
transformed_basis = np.array([[3, 4], [2, -1]])

# 创建一个变换矩阵
transformation_matrix = transformed_basis.T  # 转置以使列向量成为基向量

print("变换矩阵:")
print(transformation_matrix)

# 定义一个函数来应用变换
def apply_transformation(point):
    return np.dot(transformation_matrix, point)

# 创建图形
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))

# 绘制原始坐标系
ax1.set_title('原始坐标系')
ax1.quiver(0, 0, original_basis[0, 0], original_basis[0, 1], angles='xy', scale_units='xy', scale=1, color='r', label='基向量 [1,0]')
ax1.quiver(0, 0, original_basis[1, 0], original_basis[1, 1], angles='xy', scale_units='xy', scale=1, color='b', label='基向量 [0,1]')
ax1.set_xlim(-2, 2)
ax1.set_ylim(-2, 2)
ax1.axhline(y=0, color='k', linestyle='--', alpha=0.3)
ax1.axvline(x=0, color='k', linestyle='--', alpha=0.3)
ax1.grid(True, linestyle='--', alpha=0.7)
ax1.legend()
ax1.set_aspect('equal')

# 绘制变换后的坐标系
ax2.set_title('变换后的坐标系')
ax2.quiver(0, 0, transformed_basis[0, 0], transformed_basis[0, 1], angles='xy', scale_units='xy', scale=1, color='r', label='基向量 [3,4]')
ax2.quiver(0, 0, transformed_basis[1, 0], transformed_basis[1, 1], angles='xy', scale_units='xy', scale=1, color='b', label='基向量 [2,-1]')
ax2.set_xlim(-5, 5)
ax2.set_ylim(-5, 5)
ax2.axhline(y=0, color='k', linestyle='--', alpha=0.3)
ax2.axvline(x=0, color='k', linestyle='--', alpha=0.3)
ax2.grid(True, linestyle='--', alpha=0.7)
ax2.legend()
ax2.set_aspect('equal')

# 添加一些点并显示它们的变换
points = np.array([[1, 0], [0, 1], [1, 1], [0.5, 0.5], [-1, 0.5]])

# 在原始坐标系中绘制点
for point in points:
    ax1.plot(point[0], point[1], 'go', markersize=8)
    ax1.text(point[0] + 0.1, point[1] + 0.1, f'({point[0]},{point[1]})', fontsize=9)

# 在变换后的坐标系中绘制点
for point in points:
    transformed_point = apply_transformation(point)
    ax2.plot(transformed_point[0], transformed_point[1], 'go', markersize=8)
    ax2.text(transformed_point[0] + 0.1, transformed_point[1] + 0.1, 
             f'({transformed_point[0]:.1f},{transformed_point[1]:.1f})', fontsize=9)

# 添加单位正方形以显示变换效果
square_original = np.array([[0, 0], [1, 0], [1, 1], [0, 1]])
square_transformed = np.array([apply_transformation(p) for p in square_original])

ax1.add_patch(Polygon(square_original, alpha=0.2, color='green', label='单位正方形'))
ax2.add_patch(Polygon(square_transformed, alpha=0.2, color='green', label='变换后的正方形'))

ax1.legend(loc='upper left')
ax2.legend(loc='upper left')

plt.tight_layout()
plt.show()

# 打印一些点的变换结果
print("\n点变换示例:")
for i, point in enumerate(points):
    transformed = apply_transformation(point)
    print(f"点 {point} -> {transformed}")